package com.employ.admin.controller;

import cn.hutool.core.map.MapUtil;
import com.employ.admin.common.AuthImg;
import com.employ.admin.common.Result;
import com.employ.admin.lang.Const;
import com.employ.admin.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class AuthController extends BaseController{

    @Autowired
    Producer poroducer;
    @Resource
    private RedisUtil redisUtil;
    @GetMapping("/captcha")
    public Result captcha() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = poroducer.createText();

        BufferedImage image = poroducer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.hset(Const.CAPTCHA, key, code);
        return Result.success(MapUtil.builder().put("token",key).put("base64Img", base64Img).build());


     }
}
